<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { NDataTable, NButton, NCard } from 'naive-ui'
import baseCard from '@/components/base-card/index.vue'
import baseTable from '@/components/base-table/index.vue'
import { useMenuRecordStore } from '@/stores/menuRecord'
import { useRouter, useRoute } from 'vue-router';
import { GET_ORGN, ADD_MEET } from "@/service/apis/meet";
import { showMsg } from '@/assets/utils/tools';
import { sseService } from "@/assets/utils/sse";
import type { SSEChatParams } from "@/assets/utils/sse";
import { GET_LIST } from "../../service/apis/meet";
import { sseUrl } from "@/service/sseUrl";
// import Papa from "vue-papa-parse";
import Papa from "papaparse";
import svgIcon from '@/components/base-svgIcon/index.vue';
import { CashOutline as CashIcon } from '@vicons/ionicons5'

const router = useRouter()
const route = useRoute()
const modalTagList = ref<any[]>()
const showModal = ref(false)

const form = ref({
    time: null,
    date: null,
    person: []

})
const flag = ref('预定')

const scrollListRef = ref<any>(null)
const loading = ref(false)
//人员组织数据
const treeData: any = ref([])
//会议卡片数据
const meetList: any = ref([])
//呼叫会议传参数据
const callmeetList: any = ref([])
const scrollHeight = ref(0)
const showMenu = ref(false)

onMounted(() => {

    sseServiceOpen()
    scrollHeight.value = scrollListRef.value.offsetHeight
})
onUnmounted(() => {
    sseService.disconnect()
})

// watch(meetList,(newVal:any,oldVal:any) => {
//     console.log(newVal);
//     console.log(oldVal);



// },{deep:true,immediate:true})


//see 链接
function sseServiceOpen() {
    //   console.log(sseService);

    const onopen = () => {
        console.log("建立会议列表sse连接成功")
    }
    // 建立连接
    let sseChatParams: SSEChatParams = {
        onopen,
        url: sseUrl.video,
        onmessage: (event: MessageEvent) => {
            // 收到消息
            console.log('会议列表：', event.data);
            let fst = event.data.replace(/\\n/g, "\n")
            let strArr = fst.split(';')
            let strArr1 = strArr[1].split('\n')
            // console.log('会议列表：', strArr);
            // console.log('会议列表：', strArr1);
            debugger
            if (strArr[2] == '取消') {
                meetList.value.forEach((el: any, inedx: any) => {
                    // console.log(el);
                    // console.log(strArr1[1] == el.id);
                    if (strArr1[1] == el.id) {
                        meetList.value.splice(inedx, 1)
                    }

                })
            } else {
                const ddf = Papa.parse(fst, { header: true, delimiter: ";", newline: "\n" })
                // console.log('ddfddfddfddf', ddf, ddf.length);
                if (ddf.data.length > 0 && ddf.data[0]['类型'] == '呼叫') {
                    callmeetList.value = ddf.data
                }
                for (let index = 0; index < ddf.data.length; index++) {
                    if (ddf.data[index].id) {
                        if (ddf.data[index]['时间']) {
                            let a = ddf.data[index]['时间'].split(' ')
                            ddf.data[index]['日期'] = a[0]
                            ddf.data[index]['分钟'] = a[1]
                            let b = ddf.data[index]['人员'].replace(/\'/g, "\"");
                            const ddf11 = JSON.parse(b);
                            ddf.data[index]['人员1'] = ddf11
                            ddf.data[index]['长度'] = ddf11.length
                        }
                    }
                }

                meetList.value = meetList.value.concat(ddf.data)
            }
            console.log('meetList.value', meetList.value);

        },
        finallyHandler: () => {
            console.log("finallyHandler操作")
        }
    };
    sseService.connect(sseChatParams)


}



function confirmDate(a: any, b: any) { }


function updateCheckedKeys(a: any, b: any) {
    console.log(a, b);
    form.value.person = b
    modalTagList.value = b
}

function nativeTo(val?: any) {
    console.log('meetingmeetingmeeting', val);
    router.push({
        path: "/meeting",
        query: {
            meetId: val.id,
            meetTime: val['时间'],
            data: JSON.stringify(val['人员1'])
        }
    });
}

//获取人员组织
function getOrgin() {
    GET_ORGN().then((res: any) => {
        treeData.value = res.data
    }).catch((err) => {
        console.log(err);
    })
}
//预约会议
function addMeets() {
    console.log('meetingmeetingmeeting', form.value);
    loading.value = true
    if (form.value.date == null || form.value.time == null || form.value.person.length == 0) {
        showMsg('error', '请选择数据后在提交')
        loading.value = false
    } else {
        let p: any = {
            类型: '数据',
            内容: {
                应用名称: "我的电话",
                类型: '预约',
                时间: `${form.value.date} ${form.value.time}`,
                人员: form.value.person
            }
        }
        ADD_MEET({ params: JSON.stringify(p) }).then((res: any) => {

            if (res.stacode == 200) {
                loading.value = false
                reset()
                showModal.value = false
            }
        }).catch((err) => {
            console.log(err);

            loading.value = false
        })


    }
}
//重置表单
function reset() {
    form.value.time = null,
        form.value.date = null,
        form.value.person = []
    modalTagList.value = []
    // treeData.value = []
}
//呼叫会议
function callMeet() {
    loading.value = true
    if (form.value.person.length == 0) {
        showMsg('error', '请选择数据后在提交')
        loading.value = false
    } else {
        let p: any = {
            类型: '数据',
            内容: {
                应用名称: "我的电话",
                类型: '呼叫',
                人员: form.value.person
            }
        }
        ADD_MEET({ params: JSON.stringify(p) }).then((res: any) => {
            if (res.stacode == 200) {

            }
        }).catch((err) => {
            console.log(err);
            loading.value = false
        })

    }

    setTimeout(() => {
        callmeetNT()
    }, 1000)
}

//呼叫会议跳转
function callmeetNT() {
    // console.log('ssssssssssss', callmeetList.value, callmeetList.value[0].id, callmeetList.value[0]['人员1']);
    reset()
    loading.value = false
    showModal.value = false
    router.push({
        path: "/meeting",
        query: {
            meetId: callmeetList.value[0].id,
            meetTime: callmeetList.value[0]['时间'],
            data: JSON.stringify(callmeetList.value[0]['人员1'])
        }
    });
}



//取消会议
function cancelMeet(val: string, data: any) {
    // debugger;
    console.log(data);

    loading.value = true
    // if (form.value.person.length == 0) {
    //     showMsg('error', '请选择数据后在提交')
    //     loading.value = false
    // } else {
    let p: any = {
        类型: "数据",
        内容: {
            应用名称: "我的电话",
            meetId: data.id,
            类型: val,
        }
    }
    ADD_MEET({ params: JSON.stringify(p) }).then((res: any) => {

        if (res.stacode == 200) {
            loading.value = false
            // showModal.value = false
            // reset()
            // router.push("/meeting")
        }
    }).catch((err) => {
        console.log(err);
        loading.value = false
    })


}

function showmenu(params: any) {
    console.log(params);
    showMenu.value = !showMenu.value
}

// :show-menu="showMenu" @update:show-menu="showmenu"
</script>
<template>
    <baseCard :headShow="true">
        <template #headers>
            <span style="height: 50px;width: 50px;cursor:default; position: relative;" @click="showmenu">
                <svgIcon icon-name="#icon-icon_phone_call_" size="subSmall"></svgIcon>
                <span>可视电话</span>
                <div v-if="showMenu" style="position: absolute;top: 30px">
                    <div style="display: flex;flex-direction: column; ">
                        <div class="iconBtn1" @click="showModal = true, flag = '预定', getOrgin()">
                            <div><span class="iconfont icon-bhjmeeting " style="font-size: 20px"></span></div>
                            <div style="display:inline-block; font-size: 10px">预定</div>
                        </div>
                        <div class="iconBtn2" @click=" showModal = true, flag = '呼叫', getOrgin()">
                            <div><span class="iconfont icon-dianhua " style=""></span></div>
                            <div style="display:inline-block; font-size: 10px">及时</div>
                        </div>
                    </div>
                </div>
            </span>
        </template>
        <div style="display: flex;flex-direction: row;height: 100%;" ref="scrollListRef">
            <div v-if="meetList.length > 0" class="scrollList" style="padding: 20px;"
                :style="{ height: scrollHeight + 'px' }">
                <div class="meetCard" v-for="(m, n) in meetList" :key="n">
                    <div style="display: flex;flex-direction: row;justify-content: space-between;">
                        <!--<div class="meetCard_title_round">
                            <span class="iconfont icon-bhjmeeting" style="font-size: 30px;color: #fff;"></span>
                             <svgIcon icon-name="#icon-bhjmeeting" style="width: 1.5em;height: 1.5em;"></svgIcon> 
                        </div>-->

                        <div style="display: flex;flex-direction: column;margin-left: 15px; padding:2px 5px ;">
                            <n-tag round :bordered="false" :color="{ color: '#eee', textColor: '#000' }">
                                {{ m.日期 }}
                            </n-tag>
                            <div style="height: 1px;"></div>
                            <n-tag round :bordered="false" :color="{ color: '#eee', textColor: '#000' }">
                                {{ m.分钟 }}
                            </n-tag>
                        </div>
                        <div class="meetCard_title">
                            <n-float-button position="absolute" :top="-10" :right="-10" shape="circle">
                                <n-badge :value="m['长度']" :offset="[0, -8]">
                                    <n-icon>
                                        <span class="iconfont icon-bhjmeeting" style="color: #000;"></span>
                                    </n-icon>
                                </n-badge>
                            </n-float-button>
                        </div>
                    </div>
                    <hr style="margin: 2px;" />
                    <div style="padding:0 10px;">
                        <div style="height: 150px; overflow-y: hidden;overflow-x: hidden;  ">
                            <n-space>
                                <span v-for="(j, k) in m['人员1']" :key="k">{{ j.姓名 }} </span>
                            </n-space>
                        </div>
                    </div>
                    <div style="padding:5px 10px;cursor: pointer;">
                        <n-space>
                            <n-tag type="success" @click="nativeTo(m)" style="cursor: pointer;">
                                参会
                                <template #icon>
                                    <n-icon>
                                        <span class="iconfont icon-keshidianhua" style="font-size: 26px;"></span>
                                    </n-icon>
                                </template>
                            </n-tag>
                            <n-tag type="warning" @click="cancelMeet('取消', m)" style="cursor: pointer;">
                                取消
                                <template #icon>
                                    <!-- <n-icon :component="icon-guanbi_icon" /> -->
                                    <n-icon>
                                        <span class="iconfont icon-guanbi_icon" style=""></span>
                                    </n-icon>
                                    <!-- <span class="iconfont .icon-guanbi_icon" icon-phone-call-hang-up  style="font-size: 26px;"></span> -->
                                </template>
                            </n-tag>
                            <n-tag type="error" @click="cancelMeet('结束', m)" style="cursor: pointer;">
                                结束
                                <template #icon>
                                    <n-icon>
                                        <span class="iconfont icon-phone-call-hang-up" style="font-size: 22px;"></span>
                                    </n-icon>
                                </template>
                            </n-tag>
                        </n-space>
                    </div>
                </div>
            </div>
            <div v-else class="scrollList" style="padding: 20px;justify-content: center;align-items: center;"
                :style="{ height: scrollHeight + 'px' }">
                <n-result title="暂无可视电话" size="huge">
                    <template #icon>
                        <svgIcon icon-name="#icon-dianhua2" size="medium"></svgIcon>
                    </template>
                </n-result>
            </div>
            <!-- <div class="btnList" style="">
                <div class="btn1" @click="showModal = true, flag = '预定', getOrgin()">
                    <div><span class="iconfont icon-bhjmeeting " style="font-size: 30px;"></span></div>
                    预定电话
                </div>
                <div class="btn2" @click=" showModal = true, flag = '呼叫', getOrgin()">
                    <div><span class="iconfont icon-dianhua " style="font-size: 30px;"></span></div>
                    及时通话
                </div>
            </div> -->
        </div>
        <n-modal v-model:show="showModal" :mask-closable="false" :close-on-esc="false" style="width: 600px">
            <n-card :bordered="false" size="huge" role="dialog" aria-modal="true">

                <n-form-item label-placement="left" label="通话人">
                    <div
                        style="height: 60px;width: 100%;display: flex;flex-direction: row; overflow-y: hidden; overflow-x:scroll;">
                        <n-space :wrap="false">
                            <n-tag v-for="i in modalTagList">{{ i.label }}</n-tag>
                        </n-space>
                    </div>
                </n-form-item>
                <n-form-item v-if="flag == '预定'" label-placement="left" label="通话时间">
                    <n-time-picker size="small" v-model:formatted-value="form.time" value-format="HH:mm:ss"
                        style="margin-right: 10px;" />
                    <n-date-picker size="small" type="date" v-model:formatted-value="form.date"
                        value-format="yyyy-MM-dd" @update:value="confirmDate" :actions="['now']" />
                </n-form-item>
                <n-form-item label-placement="left" label="通讯录">
                    <n-tree block-line cascade checkable :selectable="false" :show-line="true" :data="treeData"
                        key-field="id" label-field="label" children-field="children" virtual-scroll
                        style="height: 300px" @update:checked-keys="updateCheckedKeys" />
                </n-form-item>
                <template #footer>
                    <div style="display: flex;flex-direction: row;justify-content: right; ">
                        <n-button v-if="flag == '预定'" type="primary" size='small' @click="addMeets"
                            :loading="loading">提交保存</n-button>
                        <n-button v-if="flag == '呼叫'" type="primary" size='small' @click="callMeet"
                            :loading="loading">呼叫参会</n-button>
                        <n-button type="warning" size='small' style="margin-left: 10px;"
                            @click="showModal = false, reset()">取消</n-button>
                    </div>
                </template>
            </n-card>
        </n-modal>
    </baseCard>
</template>

<style src="./index.scss" scoped></style>
